package com.gitee.limaozhi.socket.lesson03.example3;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author hzlimaozhi
 * @date 2019/08/07 08:14
 */
public class Client {

    private static AtomicInteger count = new AtomicInteger();

    private String remoteHost;
    private int remotePort;
    private String name;

    private ExecutorService executorService;
    private Socket socket;
    private HandlerContext context;

    public Client(String remoteHost, int remotePort, ExecutorService executorService) {
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
        this.name = "Client-" + count.incrementAndGet();
        this.executorService = executorService;
        start();
    }

    private void start() {
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(remoteHost, remotePort));
            System.out.println(name + "：建立连接");

            context = new HandlerContext(name, socket, executorService);
            context
                    .addLast(new InputHandler())
                    .addLast(new DecoderHandler())
                    .addLast(new ClientLogicHandler())
                    .addLast(new EncoderHandler())
                    .addLast(new OutputHandler())
                    .start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        String host = "127.0.0.1";
        int port = 8000;
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 5; i++) {
            new Client(host, port, executorService);
        }
    }

}
